package city.spring.modules.material.service.impl;

import city.spring.modules.material.entity.MaterialreceiptEntity;
import city.spring.modules.material.entity.MaterialreceiptMaterialExtEntity;
import city.spring.modules.material.repository.MaterialSettingRepository;
import city.spring.modules.material.repository.MaterialreceiptRepository;
import city.spring.modules.material.service.MaterialSettingService;
import city.spring.modules.material.service.MaterialreceiptMaterialExtService;
import city.spring.modules.material.service.MaterialreceiptService;
import city.spring.modules.material.vo.MaterialreceiptVO;
import city.spring.modules.personnel.entity.EmployeeEntity;
import city.spring.modules.personnel.repository.EmployeeRepository;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.modules.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.NonNull;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.security.Principal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Service：领用申请表
 *
 * @author 谢金婷
 * @date 2020-06-19 11:28:23
 */
@CacheConfig(cacheNames = {MaterialreceiptServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Throwable.class)
@Service
public class MaterialreceiptServiceImpl extends ServiceImpl<MaterialreceiptRepository, MaterialreceiptEntity> implements MaterialreceiptService {

    private final UserService userService;
    private final EmployeeRepository employeeRepository;
    private final MaterialSettingService materialSettingService;
    private final MaterialreceiptRepository materialreceiptRepository;
    private final EmployeeService employeeService;
    private final MaterialSettingRepository materialSettingRepository;
    private final MaterialreceiptMaterialExtService materialreceiptMaterialExtService;

    public MaterialreceiptServiceImpl(UserService userService, EmployeeRepository employeeRepository, MaterialSettingService materialSettingService, MaterialreceiptRepository materialreceiptRepository, EmployeeService employeeService, MaterialSettingRepository materialSettingRepository, MaterialreceiptMaterialExtService materialreceiptMaterialExtService) {
        this.userService = userService;
        this.employeeRepository = employeeRepository;
        this.materialSettingService = materialSettingService;
        this.materialreceiptRepository = materialreceiptRepository;
        this.employeeService = employeeService;
        this.materialSettingRepository = materialSettingRepository;
        this.materialreceiptMaterialExtService = materialreceiptMaterialExtService;
    }

    @Override
    public void saveReceipt(MaterialreceiptEntity entity, @NonNull Principal user) {

//        //设置申请领取人员为当前登录用户
//        UserEntity userEntity = userService.getUserByIdOrAccount(user.getName());
//        System.out.println("userEntity" + userEntity);
//        entity.setReceipter(userEntity.getId());
//        //设置所属部门
////        //1.根据用户id获取信息
        EmployeeEntity employeeEntity = employeeService.getById(entity.getReceipter());
//        System.out.println("employeeEntity" + employeeEntity);
////        //2.设置部门
        entity.setDepartment(employeeEntity.getOrgId());
//        System.out.println("entity.getDepartment()" + entity.getDepartment());
//        // 设置审核人申请用户主管
//        EmployeeEntity employeeDuty = employeeRepository.getDuties(employeeEntity.getOrgId());
//        entity.setDReviewer(employeeDuty.getId());
//        //审核状态为待审核
        entity.setDApprovalStatus("待审核");
        entity.setOApprovalStatus("待审核");
//        // 出库状态 未出库
        entity.setDeliveryStatus("未出库");
        entity.setReceiptStatus("未领用");

        /**
         * 库存提示：计算目前库存减去待出库后的库存
         */
        // 申请物资是 materialSettingEntity 计算这个物资的库存量
//        BigDecimal optionalQuantity = materialreceiptRepository.getOptionalQuantity(materialSettingEntity.getName()) == null ? BigDecimal.ZERO : materialreceiptRepository.getOptionalQuantity(materialSettingEntity.getName());

        // 领用数量小于最大可领用数量则保存， 否则提示
//        if (entity.getQuantity().compareTo(optionalQuantity) < 1) {
//            save(entity);
//        } else {
//            throw new RuntimeException("领用数量大于最大可领数量。当前最大可领数量: " + optionalQuantity + entity.getUnitmeasurement() + "。  保存信息失败");
//        }


        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
    }

    @Override
    public void updateReceipt(MaterialreceiptEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改

        //设置审核状态为待审核
        entity.setDApprovalStatus("待审核");
        entity.setOApprovalStatus("待审核");
        entity.setDReviewer("");
        entity.setOReviewer("");
//        Date sdate = null;
//        entity.setDReviewdate(sdate);
//        entity.setOReviewdate(sdate);
        entity.setDSuggestion("");
        entity.setOSuggestion("");
        boolean update = updateById(entity);

        if (!update) {
            throw new RuntimeException("修改信息失败");
        }

        materialreceiptRepository.updateReviewdate(entity.getId());
    }

    @Override
    public void deleteReceipt(String primaryKey) {
        removeById(primaryKey);
        List<MaterialreceiptMaterialExtEntity> materialExtEntities = materialreceiptMaterialExtService.getByMaterialreceiptId(primaryKey);
        if (!materialExtEntities.isEmpty()) {
            List<String> materialId = materialExtEntities.stream().map(MaterialreceiptMaterialExtEntity::getId).collect(Collectors.toList());
            materialreceiptMaterialExtService.removeByIds(materialId);
        }
    }

    @Override
    public void deleteReceipt(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }

    @Override
    public MaterialreceiptEntity getById(String id) {
        return materialreceiptRepository.getById(id);
    }

    @Override
//    public IPage<MaterialreceiptEntity> getMaterialreceiptPass(Pageable pageable) {
//        IPage<MaterialreceiptEntity> page = MyBatisUtils.toPage(pageable);
//        return materialreceiptRepository.getMaterialreceiptPass(page, lambdaQuery().getWrapper());
//    }
    public IPage<MaterialreceiptVO> getMaterialreceiptPass(Page<? extends MaterialreceiptEntity> page, Wrapper<? extends MaterialreceiptEntity> wrapper) {
        return materialreceiptRepository.getMaterialreceiptPass(page, wrapper);
    }

    @Override
    public IPage<MaterialreceiptVO> listPage(Page<? extends MaterialreceiptEntity> page, Wrapper<? extends MaterialreceiptEntity> wrapper) {
        return baseMapper.listPage(page, wrapper);
    }

    @Override
    public IPage<MaterialreceiptVO> approvalListPage(Page<? extends MaterialreceiptEntity> page, Wrapper<? extends MaterialreceiptEntity> wrapper) {
        return baseMapper.approvalListPage(page, wrapper);
    }

    /**
     * 统计最大可领用数量
     * 现有库存-待出库数量（领用待审核数量）
     *
     * @param name
     * @return
     */
    @Override
    public BigDecimal getOptionalQuantity(String name) {
        return materialreceiptRepository.getOptionalQuantity(name);
    }

    @Override
    public IPage<MaterialreceiptVO> oapprovalListPage(Page<? extends MaterialreceiptEntity> page, Wrapper<? extends MaterialreceiptEntity> wrapper) {
        return baseMapper.oapprovalListPage(page, wrapper);
    }

    @Override
    public void checkReceipt(String id, MaterialreceiptEntity entity) {
        entity.setReceiptStatus("已领用");
        materialreceiptRepository.checkReceipt(id, entity);
    }

}